package com.lky.marshall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.lky.common.to.es.SkuEsModle;
import com.lky.marshall.search.config.MarshallElasticSearchConfig;
import com.lky.marshall.search.constant.EsConstant;
import com.lky.marshall.search.service.MallSearchService;
import com.lky.marshall.search.vo.SearchParams;
import com.lky.marshall.search.vo.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by
 * autor : Marshall lky
 * datetime: 2021/4/16 13:35
 */
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public SearchResult search(SearchParams searchParams) {
        //动态构建出查询需要的DSL语句
        SearchResult request = null;
        //1.准备检索请求
        SearchRequest searchRequest = buildSearchRequest(searchParams);

        try {
            //2.执行检索请求
            SearchResponse response = restHighLevelClient.search(searchRequest, MarshallElasticSearchConfig.COMMON_OPTIONS);
            //3.分析响应数据，封装成需要的格式
            request = buildSearchResult(response,searchParams);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return request;
    }

    /**
     * 构建结果数据
     *
     * @param response
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse response,SearchParams searchParams) {
        SearchResult searchResult = new SearchResult();
        //返回所有查询到的商品
        SearchHit[] hits = response.getHits().getHits();
        List<SkuEsModle> skuEsModles = new ArrayList<>();
        if (hits!=null&&hits.length>0) {
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModle skuEsModle = JSON.parseObject(sourceAsString, SkuEsModle.class);
                if (!StringUtils.isEmpty(searchParams.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String highContext = skuTitle.getFragments()[0].string();
                    skuEsModle.setSkuTitle(highContext);
                }
                skuEsModles.add(skuEsModle);
            }
        }
        searchResult.setProducts(skuEsModles);
        //当前所有商品涉及到的所有属性信息
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            attrVo.setAttrId(Long.parseLong(bucket.getKeyAsString()));
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);
            List<String> attrValue = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(item->{
                return item.getKeyAsString();
            }).collect(Collectors.toList());
            attrVo.setAttrValue(attrValue);
            attrVos.add(attrVo);
        }
        searchResult.setAttrs(attrVos);
        //当前所有商品涉及到的所有分类信息
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        List<SearchResult.CatelogVo> catelogVos = new ArrayList<>();
        List<? extends Terms.Bucket> catelogBuckets = catalog_agg.getBuckets();
        for (Terms.Bucket bucket : catelogBuckets) {
            SearchResult.CatelogVo catelogVo = new SearchResult.CatelogVo();
            String keyAsString = bucket.getKeyAsString();
            catelogVo.setCatelogId(Long.parseLong(keyAsString));
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            catelogVo.setCatelogName(catalog_name_agg.getBuckets().get(0).getKeyAsString());
            catelogVos.add(catelogVo);
        }
        searchResult.setCatelogs(catelogVos);
        //当前所有商品涉及到的所有品牌信息
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        List<? extends Terms.Bucket> brandBuckets = brand_agg.getBuckets();
        for (Terms.Bucket brandBucket : brandBuckets) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            String brandId = brandBucket.getKeyAsString();
            brandVo.setBrandId(Long.parseLong(brandId));
            ParsedStringTerms brand_img_agg = brandBucket.getAggregations().get("brand_img_agg");
            String brandImg = brand_img_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);
            ParsedStringTerms brand_name_agg = brandBucket.getAggregations().get("brand_name_agg");
            String brandName = brand_name_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);
            brandVos.add(brandVo);
        }
        searchResult.setBrands(brandVos);

        long total = response.getHits().getTotalHits().value;
        searchResult.setTotal(total);
        int totalPages = (int) (total%EsConstant.PAGE_SIZE == 0?total/EsConstant.PAGE_SIZE:(total/EsConstant.PAGE_SIZE)+1);
        searchResult.setTotalPages(totalPages);
        searchResult.setPageNum(searchParams.getPageNum());
        List<Integer> pageList = new ArrayList<>();
        for (int i = 1; i <= totalPages ; i++) {
            pageList.add(i);
        }
        searchResult.setPageNavs(pageList);

        System.out.println(searchResult.toString());
        return searchResult;
    }

    /**
     * 准备检索请求
     *
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParams searchParams) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();//构建dsl语句的
        /**
         * 查询 ：模糊匹配，过滤（属性，分类，品牌，价格区间
         */
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //1.1 must
        if (!StringUtils.isEmpty(searchParams.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", searchParams.getKeyword()));
        }
        //1.2 filter  按照三级分类查询
        if (searchParams.getCatalog3Id() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("catelogId", searchParams.getCatalog3Id()));
        }
        //filter  按照品牌id查询
        if (searchParams.getBrandId() != null && searchParams.getBrandId().size() > 0) {
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", searchParams.getBrandId()));
        }
        //filter  按照所有指定的属性进行查询
        if (searchParams.getAttrs() != null && searchParams.getAttrs().size() > 0) {
            for (String attrstr : searchParams.getAttrs()) {
                //attrs=1_5寸:8寸&attrs=2_16G:8G
                BoolQueryBuilder nestedboolQueryBuilder = QueryBuilders.boolQuery();
                String[] s = attrstr.split("_");
                String attrId = s[0];  //检索属性id
                String[] values = s[1].split(":"); //检索属性值
                nestedboolQueryBuilder.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedboolQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue", values));
                //每一个必须生成一个嵌入式查询e
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedboolQueryBuilder, ScoreMode.None);
                boolQueryBuilder.filter(nestedQuery);
            }
        }
        //filter  按照是否有库存进行查询
        if (searchParams.getHasStock()!=null) {
            boolQueryBuilder.filter(QueryBuilders.termsQuery("hasStock", searchParams.getHasStock() == 1));
        }
        //filter  按照价格区间检索
        if (!StringUtils.isEmpty(searchParams.getSkuPrice())) {
            //1_500/_500/500_
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] price = searchParams.getSkuPrice().split("_");
            if (price.length == 2) {
                //区间   1<price<500
                rangeQuery.gte(price[0]).lte(price[1]);
            } else if (price.length == 1) {
                if (searchParams.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(price[0]);
                }
                if (searchParams.getSkuPrice().endsWith("_")) {
                    rangeQuery.gte(price[0]);
                }
            }
            boolQueryBuilder.filter(rangeQuery);
        }
        sourceBuilder.query(boolQueryBuilder);
        /**
         * 排序，分页，高亮
         */
        //排序
        if (!StringUtils.isEmpty(searchParams.getSort())){
            String sort = searchParams.getSort();
            //sort = hotScore_asc/desc
            String[] params = sort.split("_");
            SortOrder order = params[1].equalsIgnoreCase("asc")?SortOrder.ASC:SortOrder.DESC;
            sourceBuilder.sort(params[0], order);
        }
        //分页
        sourceBuilder.from((searchParams.getPageNum()-1)*EsConstant.PAGE_SIZE);  //（页码-1）*size
        sourceBuilder.size(EsConstant.PAGE_SIZE);
        //高亮
        if (!StringUtils.isEmpty(searchParams.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }
        /**
         * 聚合分析
         */
        //品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg").field("brandId").size(10);
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brand_agg);
        //分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catelogId").size(10);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catelogName").size(1));
        sourceBuilder.aggregation(catalog_agg);
        //属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(10); //子聚合 attr_id_agg
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));   //attr_id_agg的子聚合attr_name_agg
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));//attr_id_agg的子聚合attr_value_agg
        attr_agg.subAggregation(attr_id_agg); //attr聚合加入id子聚合
        sourceBuilder.aggregation(attr_agg);

        System.out.println("检索检索dsldsldsldsl:"+sourceBuilder.toString());
        return new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
    }
}
